import menuButton from './menuButton';
import formula from '../global/formula';
import Store from '../store';
import flatpickr from 'gq-flatpickr'
import dayjs from "dayjs";
import { update, datenum_local } from '../global/format';
import { setCellValue, setCellFormat } from '../global/api';
// nby 新增“年月”
const  monthSelectPlugin = require('../assets/monthSelect')
// require('../assets/monthSelect/style.css')   //需要在index.html或者main.js中引入


const fitFormat = (formatStr) => {
    let dateFormat = formatStr.replace(/y/g, 'Y');
    dateFormat = dateFormat.replace(/d/g, 'D');
    dateFormat = dateFormat.replace(/h/g, 'H');

    dateFormat = dateFormat.replace(/上午\/下午/g, 'A');
    dateFormat = dateFormat.replace(/上午/g, 'A');
    dateFormat = dateFormat.replace(/下午/g, 'A');

    dateFormat = dateFormat.replace(/AM\/PM/g, 'A');
    dateFormat = dateFormat.replace(/AM/g, 'A');
    dateFormat = dateFormat.replace(/PM/g, 'A');
    dateFormat = dateFormat.replace(/\"/g, '');

    if (dateFormat.includes('A')) {
        dateFormat = dateFormat.replace(/H/g, 'h');
    }
    return dateFormat
}

const cellDatePickerCtrl = {
    cellFocus: function (r, c, cell) {
        let isChiinaYear = false

        let row = Store.visibledatarow[r],
            row_pre = r == 0 ? 0 : Store.visibledatarow[r - 1];
        let col = Store.visibledatacolumn[c],
            col_pre = c == 0 ? 0 : Store.visibledatacolumn[c - 1];

        let margeset = menuButton.mergeborer(Store.flowdata, r, c);
        let type = cell.ct.fa || 'YYYY-MM-DD';
        let defaultDate = update('yyyy-MM-dd hh:mm:ss', cell.v);
        let dateFormat = fitFormat(type);
        let enableTime = false;
        let noCalendar = false;
        let enableSeconds = false;
        let time_24hr = true;
        let hasChineseTime = false;


        if (!!margeset) {
            row = margeset.row[1];
            row_pre = margeset.row[0];

            col = margeset.column[1];
            col_pre = margeset.column[0];
        }

        $(".cell-date-picker").show().css({
            width: col - col_pre + 1,
            height: row - row_pre + 1,
            left: col_pre,
            top: row_pre
        })

        if (/[上午下午]/.test(type)) {
            hasChineseTime = true
        }
        if (/[Hhms]/.test(dateFormat)) {
            enableTime = true;
        }
        if (!/[YMD]/.test(dateFormat)) {
            noCalendar = true;
        }
        if (/s/.test(dateFormat)) {
            enableSeconds = true;
        }
        if (/A/.test(dateFormat)) {
            time_24hr = false;
        }
        // nby 新增“年月”
        let pluginsArr = []
        if(/Y.m.z/.test(dateFormat)){
            isChiinaYear = true
        }
        if(/Y.m/.test(dateFormat)){
            pluginsArr = [new monthSelectPlugin({
                // shorthand: true, //defaults to false
                dateFormat: "Y.m", //defaults to "F Y"
                // altFormat: "Y F", //defaults to "F Y"
            })]
            enableTime = false;
        }
        const fp = flatpickr('#luckysheet-input-box', {
            disableMobile: true,//解决控件移动端不显示的问题。
            allowInput: false,
            noCalendar,
            enableSeconds,
            enableTime,
            dateFormat,
            time_24hr,
            defaultDate,
            // nby 添加插件，支持“年月”
            plugins:pluginsArr,
            onClose() {
                // nby 解决移动端切换值时，软键盘弹出闪一下的问题，把下面注释，只保留销毁
                // const inputDom = document.createElement('input')
                // document.body.appendChild(inputDom)
                // inputDom.focus()
                // setTimeout(() => {
                //     document.body.removeChild(inputDom)
                    fp.destroy()
                // }, 0);
            },
            parseDate: (datestr, format) => {
                // return dayjs(datestr).toDate();
                // 源码如上。
                // nby 月-日 格式 10-25 _qjp_
                if(/^\d{4}-/.test(datestr) === false){
                    if(cell?.ct?.fa === 'M"月"d"日"' || cell?.ct?.fa == 'M-d' || cell?.ct?.fa == 'MM-dd' || (cell?.ct?.fa == "yyyy-MM-dd" && /^\d{2}-\d{2}$/.test(datestr))){
                        return dayjs(new Date().getFullYear() + datestr).toDate();
                    }
                }
                return dayjs(datestr).toDate();
            },
            formatDate: (date, format, locale) => {
                if (hasChineseTime) {
                    return dayjs(date).format(format).replace('AM', '上午').replace('PM', '下午')
                } 
                return dayjs(date).format(format);
            },
            // 源码使用的是onchange
            /*         onChange: function (selectedDates, dateStr) {
                let currentVal = datenum_local(new Date(selectedDates))
                // nby 新增“年月”
                if(pluginsArr.length > 0){
                    dateStr = dayjs(selectedDates).format('YYYY-MM')
                }             
                $("#luckysheet-rich-text-editor").html(dateStr);
                setCellValue(r, c, currentVal, { isRefresh: false })
                setCellFormat(r, c, 'ct', cell.ct)
                if (!enableTime) {
                    formula.updatecell(Store.luckysheetCellUpdate[0], Store.luckysheetCellUpdate[1]);
                }
            }, */
            onValueUpdate(selectedDates,dateStr){
                let currentVal = datenum_local(new Date(selectedDates))
                // nby 新增“年月”
                if(pluginsArr.length > 0){
                    dateStr = dayjs(selectedDates).format('YYYY-MM')
                }           
                if(isChiinaYear){
                    let arr = dateStr.split('-')
                    if(arr.length == 2){
                        dateStr = arr[0] + '年' + arr[1] + '月'
                    }
                }
                
                $("#luckysheet-rich-text-editor").html(dateStr);
                setCellValue(r, c, currentVal, { isRefresh: false })
                setCellFormat(r, c, 'ct', cell.ct)
                if (!enableTime) {
                    formula.updatecell(Store.luckysheetCellUpdate[0], Store.luckysheetCellUpdate[1]);
                }
            }
        });

        $("#luckysheet-input-box").click();

        return
    },
}

export default cellDatePickerCtrl;
